function findLoopEndIndex(s, begin) {
    for (var i = begin + 1; i < s.length; i++) {
        if (s[i] === ']') return i;
    }
}

const Interpreter = function () {
    var stacks = [[0], [0], [0]];
    var cur_stack_idx = 0;//current stack index
    var stack = stacks[cur_stack_idx];//current stack
    return {
        read: function (input) {
            var out = '';
            var loops = []
            for (var i = 0; i < input.length; i++) {
                var cmd = input[i];
                switch (cmd) {
                    case '+': if (stack.length) stack[stack.length - 1]++; break;
                    case '-': if (stack.length) stack[stack.length - 1]--; break;
                    case '<':
                        var temp = stack.pop();
                        var idx = (cur_stack_idx + 2) % 3;
                        if (temp != undefined) stacks[idx].push(temp);
                        break;
                    case '>':
                        var temp = stack.pop();
                        var idx = (cur_stack_idx + 1) % 3;
                        if (temp != undefined) stacks[idx].push(temp);
                        break;
                    case '*':
                        stack.push(0); break;
                    case '^': stack.pop(); break;
                    case '#': cur_stack_idx = (cur_stack_idx + 1) % 3; stack = stacks[cur_stack_idx]; break;
                    case ',':
                        var inp_num = input.slice(i + 1).match(/\d+/)[0];
                        i += inp_num.length;
                        stack.push(+inp_num);
                        break;
                    case '.': out += stack.length ? stack[stack.length - 1] : ''; break;
                    case '[':
                        if (stack[stack.length - 1] > 0) { loops.push(i); } else {
                            i = findLoopEndIndex(input, i);
                        }
                        break;
                    case ']':
                        if (stack[stack.length - 1] > 0) i = loops[loops.length - 1];
                        else { loops.pop(); }
                        break;
                }
            }
            return out;
        }
    };
}

var inter = new Interpreter();
console.log(inter.read('*++.'))